package core

import (
	"fast-go/internal/routers"
	_ "github.com/go-sql-driver/mysql"
	"gopkg.in/natefinch/lumberjack.v2"
	"log"
	"net/http"
	"time"
)

type Init struct{}

// app启动服务
func (i Init) AppStart() error {
	// 加载配置参数
	loadErr := i.LoadConfig()
	if loadErr != nil {
		return loadErr
	}
	// 加载日志服务
	if err := i.LoadLogger(); err != nil {
		return err
	}
	// 加载数据库引擎
	if databaseEngineErr := i.LoadDBEngine(); databaseEngineErr != nil {
		return databaseEngineErr
	}
	// 启动服务
	err := i.HttpStart()
	if err != nil {
		return err
	}
	return nil
}

// 挂载全局配置
func (i Init) LoadConfig() error {
	setting, err := NewSetting()
	if err != nil {
		return err
	}
	err = setting.ReadSection("Server", &ServerSetting)
	if err != nil {
		return err
	}
	err = setting.ReadSection("App", &AppSetting)
	if err != nil {
		return err
	}
	err = setting.ReadSection("Database", &DatabaseSetting)
	if err != nil {
		return err
	}
	return nil
}

// 挂载数据库引擎
func (i Init) LoadDBEngine() error {
	DB, err := NewDBEngineManager()
	DBEngine = DB
	return err
}

// 挂在日志服务
func (i Init) LoadLogger() error {
	Log = NewLogger(&lumberjack.Logger{
		Filename:   AppSetting.LogFileName,
		MaxSize:    600,
		MaxAge:     10,
		MaxBackups: 0,
		LocalTime:  true,
		Compress:   false,
	}, "", log.LstdFlags).WithCaller(2)
	return nil
}

// 服务器启动
func (i Init) HttpStart() error {
	router := routers.Router()
	s := &http.Server{
		Addr:              ":" + ServerSetting.HttpPort,
		Handler:           router,
		TLSConfig:         nil,
		ReadTimeout:       10 * time.Second,
		ReadHeaderTimeout: 10 * time.Second,
		WriteTimeout:      10 * time.Second,
		IdleTimeout:       10 * time.Second,
		MaxHeaderBytes:    1 << 20,
		TLSNextProto:      nil,
		ConnState:         nil,
		ErrorLog:          nil,
		BaseContext:       nil,
		ConnContext:       nil,
	}
	err := s.ListenAndServe()
	if err != nil {
		return err
	}
	return nil
}
